/*
 * SongListTablePanel.java
 *
 * Created on June 20, 2005, 8:27 PM
 */
package com.bff.slimserver.musicjukebox.ui.components.favorites;

import com.bff.slimserver.music.exceptions.PlaylistException;
import com.bff.bjj.ui.component.ColorProperties;
import com.bff.slimserver.musicjukebox.ui.components.HideTableColumnListener;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.ui.components.BitrateCellRenderer;
import com.bff.slimserver.musicjukebox.ui.components.LengthCellRenderer;
import com.bff.bjj.ui.component.BJJPanel;
import com.bff.slimserver.musicjukebox.ui.components.SongCellRenderer;
import com.bff.slimserver.musicjukebox.ui.components.SongScrollPane;
import com.bff.slimserver.musicjukebox.ui.components.SongTable;
import com.bff.slimserver.musicjukebox.ui.components.TrackCellRenderer;
import com.bff.slimserver.utils.TableSorter;
import com.bff.bjj.utils.Utils;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.swing.ScrollPaneConstants;
import org.bff.slimserver.SlimPlaylist;
import org.bff.slimserver.exception.SlimException;
import org.bff.slimserver.musicobjects.SlimPlayableObject;
import org.bff.slimserver.musicobjects.SlimPodcastAudioDetails;

/**
 *
 * @author  Bill
 */
public class FavoritesTablePanel
        extends BJJPanel
        implements ComponentListener {

    private FavoritesTableModel tableModel;
    private SlimPlaylist playlist;
    private TableSorter tableSorter;
    private Container parent;
    private JukeboxProperties jp;
    private SlimPodcastAudioDetails podcast;

    /** Creates new form SongListTablePanel */
    public FavoritesTablePanel() {
        super();
        jp = JukeboxProperties.getInstance();

        tableSorter = new TableSorter(tableModel);
        parent = this;

        try {
            this.playlist = jp.getPlaylist();
        } catch (PlaylistException ex) {
            Logger.getLogger(FavoritesTablePanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();

        setScrollbarSize();
        addComponentListener(this);
        infoTableScrollPane.getViewport().setBackground(ColorProperties.LIST_BACKGROUND_EVEN);

        loadProgressBar.setVisible(false);

        //new Thread(new RefreshThread()).start();

////        
////        FillPainter bgPainter = new FillPainter();
////        StampPainter fgPainter = new StampPainter();
////        WatermarkViewport wvp = new WatermarkViewport(bgPainter, fgPainter);
////        wvp.setView(infoTable);
////        infoTableScrollPane.setViewport(wvp);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnPanel = new com.bff.bjj.ui.component.BJJPanel();
        jPanel1 = new com.bff.bjj.ui.component.BJJPanel();
        btnAddToPlaylist = new com.bff.bjj.ui.component.BJJButton();
        btnPlayNext = new com.bff.bjj.ui.component.BJJButton();
        btnClearAndPlay = new com.bff.bjj.ui.component.BJJButton();
        jPanel2 = new com.bff.bjj.ui.component.BJJPanel();
        infoTableScrollPane = new SongScrollPane(infoTable);
        infoTable = new SongTable();
        jPanel3 = new com.bff.bjj.ui.component.BJJPanel();
        loadProgressBar = new javax.swing.JProgressBar();

        setLayout(new java.awt.BorderLayout());

        btnPanel.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.GridBagLayout());

        btnAddToPlaylist.setText("Add to Playlist");
        btnAddToPlaylist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddToPlaylistActionPerformed(evt);
            }
        });
        jPanel1.add(btnAddToPlaylist, new java.awt.GridBagConstraints());

        btnPlayNext.setText("Play Next");
        btnPlayNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayNextActionPerformed(evt);
            }
        });
        jPanel1.add(btnPlayNext, new java.awt.GridBagConstraints());

        btnClearAndPlay.setText("Clear and Play");
        btnClearAndPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearAndPlayActionPerformed(evt);
            }
        });
        jPanel1.add(btnClearAndPlay, new java.awt.GridBagConstraints());

        btnPanel.add(jPanel1, java.awt.BorderLayout.SOUTH);

        add(btnPanel, java.awt.BorderLayout.SOUTH);

        jPanel2.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                jPanel2ComponentResized(evt);
            }
        });
        jPanel2.setLayout(new java.awt.BorderLayout());

        infoTableScrollPane.setBackground(ColorProperties.LIST_BACKGROUND_EVEN);
        infoTableScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        infoTableScrollPane.setMaximumSize(new java.awt.Dimension(800, 32767));
        infoTableScrollPane.setPreferredSize(new java.awt.Dimension(200, 200));

        infoTable.setBackground(ColorProperties.PANEL_BACKGROUND);
        infoTable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        infoTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        infoTable.setOpaque(false);
        infoTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                infoTableMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                infoTableMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                infoTableMouseReleased(evt);
            }
        });
        infoTable.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                infoTableComponentResized(evt);
            }
        });
        infoTableScrollPane.setViewportView(infoTable);

        jPanel2.add(infoTableScrollPane, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.BorderLayout());

        loadProgressBar.setIndeterminate(true);
        loadProgressBar.setString("Loading Favorites");
        loadProgressBar.setStringPainted(true);
        jPanel3.add(loadProgressBar, java.awt.BorderLayout.NORTH);

        jPanel2.add(jPanel3, java.awt.BorderLayout.SOUTH);

        add(jPanel2, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents
    private void infoTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_infoTableMouseReleased
        infoTableMousePressed(evt);
	}//GEN-LAST:event_infoTableMouseReleased

    private void infoTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_infoTableMousePressed
        if (SwingUtilities.isRightMouseButton(evt)) {
            int row = infoTable.rowAtPoint(evt.getPoint());
            if (row > -1) {
                //@TODO Fix this
                /*
                ListSelectionModel selectionModel = infoTable.getSelectionModel();
                selectionModel.setSelectionInterval(row, row);
                SlimPodcastAudioDetails song = tableModel.getPodcast(tableSorter.modelIndex(row));
                SonglistPopupMenu popupMenu = new SonglistPopupMenu(Utils.getParentComponent(this), getPlaylist(), song);
                if (evt.isPopupTrigger()) {
                popupMenu.show(evt.getComponent(),
                evt.getX(), evt.getY());
                }
                 */
            }
        } else {
            if (infoTable.getSelectedRows().length == 1) {
                btnClearAndPlay.setEnabled(true);
                SlimPodcastAudioDetails song = tableModel.getPodcast(tableSorter.modelIndex(infoTable.getSelectedRow()));

            } else {
                btnClearAndPlay.setEnabled(false);

                SlimPodcastAudioDetails song = null;
                int[] songs = infoTable.getSelectedRows();
                for (int i = 0; i < songs.length; i++) {
                    int songIndex = songs[i];
                    song = tableModel.getPodcast(tableSorter.modelIndex(songIndex));

                }
            }
        }
    }//GEN-LAST:event_infoTableMousePressed

    private void infoTableComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_infoTableComponentResized
        setScrollbarSize();
    }//GEN-LAST:event_infoTableComponentResized

    private void jPanel2ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPanel2ComponentResized
        //infoTableScrollPane.setPreferredSize(jPanel2.getSize());
    }//GEN-LAST:event_jPanel2ComponentResized

    private void infoTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_infoTableMouseClicked
        if (evt.getClickCount() == 2) {
            try {
                int row = infoTable.rowAtPoint(evt.getPoint());
                SlimPodcastAudioDetails song = tableModel.getPodcast(tableSorter.modelIndex(row));
                this.setCursor(Utils.getHourglassCursor());
                getPlaylist().addItem(song);
//                lblActions.setText(song.getTitle() + " added into the playlist.");
            } catch (SlimException ex) {
                Logger.getLogger(FavoritesTablePanel.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                this.setCursor(Utils.getNormalCursor());
            }
        }
    }//GEN-LAST:event_infoTableMouseClicked

    private void btnAddToPlaylistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddToPlaylistActionPerformed
        this.setCursor(Utils.getHourglassCursor());
        try {
            int rows[] = infoTable.getSelectedRows();

            if (rows.length > 1) {
                List<SlimPlayableObject> list = new ArrayList<SlimPlayableObject>();
                for (int i = 0; i < rows.length; i++) {
                    SlimPodcastAudioDetails song = tableModel.getPodcast(tableSorter.modelIndex(rows[i]));
                    list.add(song);
                }
                try {
                    getPlaylist().addItems(list);
                    //                  lblActions.setText(rows.length + " songs added to the playlist.");
                } catch (SlimException ex) {
                    Logger.getLogger(FavoritesTablePanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    SlimPodcastAudioDetails song = tableModel.getPodcast(tableSorter.modelIndex(rows[0]));
                    getPlaylist().addItem(song);
//                    lblActions.setText(song.getTitle() + " added to the playlist.");
                } catch (SlimException ex) {
                    Logger.getLogger(FavoritesTablePanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } finally {
            this.setCursor(Utils.getNormalCursor());
        }
    }//GEN-LAST:event_btnAddToPlaylistActionPerformed

private void btnPlayNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayNextActionPerformed
    this.setCursor(Utils.getHourglassCursor());
    try {
        SlimPodcastAudioDetails song = null;
        int rows[] = infoTable.getSelectedRows();

        for (int i = 0; i < rows.length; i++) {
            try {
                song = tableModel.getPodcast(tableSorter.modelIndex(rows[i]));
                getPlaylist().insertItem(song);
            } catch (SlimException ex) {
                Logger.getLogger(FavoritesTablePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        /*
        if (rows.length > 1) {
        lblActions.setText(rows.length + " songs inserted into the playlist.");
        } else {
        lblActions.setText(song.getTitle() + " inserted into the playlist.");
        }
         */
    } finally {
        this.setCursor(Utils.getNormalCursor());
    }
}//GEN-LAST:event_btnPlayNextActionPerformed

private void btnClearAndPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearAndPlayActionPerformed
    this.setCursor(Utils.getHourglassCursor());
    try {
        SlimPodcastAudioDetails song = null;
        int rows[] = infoTable.getSelectedRows();

        if (rows.length > 1) {
//            lblActions.setText("More than one song cannot be selected for clear and play.");
            return;
        }

        for (int i = 0; i < rows.length; i++) {
            try {
                song = tableModel.getPodcast(tableSorter.modelIndex(rows[i]));
                getPlaylist().insertItem(song);
            } catch (SlimException ex) {
                Logger.getLogger(FavoritesTablePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        /*
        if (rows.length > 1) {
        lblActions.setText(rows.length + " songs inserted into the playlist.");
        } else {
        lblActions.setText(song.getTitle() + " inserted into the playlist.");
        }
         */
    } finally {
        this.setCursor(Utils.getNormalCursor());
    }
}//GEN-LAST:event_btnClearAndPlayActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddToPlaylist;
    private javax.swing.JButton btnClearAndPlay;
    private javax.swing.JPanel btnPanel;
    private javax.swing.JButton btnPlayNext;
    private javax.swing.JTable infoTable;
    private javax.swing.JScrollPane infoTableScrollPane;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JProgressBar loadProgressBar;
    // End of variables declaration//GEN-END:variables

    public void setPodcasts(Collection<SlimPodcastAudioDetails> songs) {
        setModel(new FavoritesTableModel(songs));
    }

    private void setModel(FavoritesTableModel tableModel) {
        this.tableModel = tableModel;

        JTableHeader tableHeader = infoTable.getTableHeader();
        tableHeader.setBackground(ColorProperties.TABLE_HEADER_BACKGROUND);
        tableHeader.setFont(new Font(tableHeader.getFont().getFontName(), Font.BOLD, tableHeader.getFont().getSize()));
        tableSorter.setSortingStatus(tableModel.getSortColumn(), TableSorter.ASCENDING);
        tableSorter.setTableModel(tableModel);
        tableSorter.setTableHeader(infoTable.getTableHeader());

        infoTable.setModel(tableSorter);
        new HideTableColumnListener(infoTable);
        //infoTable.addMouseListener(new HideTableColumnListener())

        int width = 0;

        TableColumn tc = infoTable.getColumnModel().getColumn(tableModel.getLengthColumnIndex());
        tc.setCellRenderer(new LengthCellRenderer());
        width += tc.getWidth();

        if (tableModel.getIDColumnIndex() > -1) {
            tc = infoTable.getColumnModel().getColumn(tableModel.getIDColumnIndex());
            tc.setCellRenderer(new SongCellRenderer());
        }

        if (tableModel.getTitleColumnIndex() > -1) {
            tc = infoTable.getColumnModel().getColumn(tableModel.getTitleColumnIndex());
            tc.setCellRenderer(new SongCellRenderer());
        }
        /*
        if(tableModel.getGenreColumnIndex() > -1) {
        tc = infoTable.getColumnModel().getColumn(tableModel.getGenreColumnIndex());
        tc.setCellRenderer(new SongCellRenderer());
        width+=tc.getWidth();
        }
         */
        if (tableModel.getLengthColumnIndex() > -1) {
            tc = infoTable.getColumnModel().getColumn(tableModel.getLengthColumnIndex());
            tc.setCellRenderer(new BitrateCellRenderer());
            width += tc.getWidth();
        }

        if (tableModel.getDateColumnIndex() > -1) {
            tc = infoTable.getColumnModel().getColumn(tableModel.getDateColumnIndex());
            tc.setCellRenderer(new TrackCellRenderer());
            width += tc.getWidth();
        }


        setTableSize();
        Utils.autoResizeTable(infoTable, true, 25);
        setTableSize();

    }

    private void setTableSize() {
        infoTable.setPreferredSize(new Dimension(this.getWidth() - 0, (int) infoTable.getRowHeight() * infoTable.getRowCount()));
    }

    public SlimPlaylist getPlaylist() {
        return playlist;
    }

    public void setPlaylist(SlimPlaylist playlist) {
        this.playlist = playlist;
    }

    /**
     * @return the podcast
     */
    public SlimPodcastAudioDetails getPodcast() {
        return podcast;
    }

    /**
     * @param podcast the podcast to set
     */
    public void setPodcast(SlimPodcastAudioDetails podcast) {
        this.podcast = podcast;
    }

    private class CenterCellRenderer extends SongCellRenderer {

        CenterCellRenderer() {
            setHorizontalAlignment(SwingConstants.CENTER);
        }
    }

    private void setScrollbarSize() {
        int width = infoTable.getWidth() + 2;
        int height = jPanel2.getHeight() - 5;
        int maxWidth = jPanel2.getWidth() - 5;

        if (infoTable.getHeight() > height && width < maxWidth) {
            width += 18;
        }

        if (width > maxWidth) {
            width = maxWidth;
        }
        infoTableScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        infoTableScrollPane.setPreferredSize(new Dimension(width, height));
        infoTableScrollPane.setSize(new Dimension(width, height));
        jPanel2.revalidate();
    }

    public void componentHidden(ComponentEvent arg0) {
        //dont care
    }

    public void componentMoved(ComponentEvent arg0) {
        //dont care
    }

    public void componentResized(ComponentEvent arg0) {
        setTableSize();
    }

    public void componentShown(ComponentEvent arg0) {
        //dont care
    }

    public void setProgressBarVisible(boolean visible) {
        loadProgressBar.setVisible(visible);
    }
}
